<?php
/**
 * description
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     weiyizheng
 * @date       2022/11/8
 * @time       2:13 下午
 */

namespace Buu\Modules\EsStandard\Controllers;


use App\Admin\Extensions\Tools\UserButton;
use App\Http\Controllers\Controller;
use App\Models\DbInstance;
use App\Models\DbTables;
use App\Models\EsColumnBindShip;
use App\Models\EsFilterRule;
use App\Models\EsIndex;
use App\Models\EsInstance;
use App\Models\EsSourceMapping;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form\Footer;
use Encore\Admin\Form\NestedForm;
use Encore\Admin\Form\Tools;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class EsIndexController extends Controller
{
	protected $title = "Es索引管理";

	public function index(Content $content)
	{
		return $content
			->title($this->title)
			->description()
			->body($this->grid());
	}

	protected function grid()
	{
		$grid = new Grid(new EsIndex());
		$grid->paginate(50);
		$grid->disableFilter();
		$grid->disableExport();
		$grid->disableBatchActions();
		$grid->disableCreateButton();

		$grid->tools(function (Grid\Tools $tool) {
			$tool->append(new UserButton(UserButton::TYPE_HREF, 'add', '新增'));
		});
		$grid->column('id', 'ID');
		$grid->column('es_instance_id', 'Es实例')->display(function () {
			return EsInstance::find($this->es_instance_id)->name;
		})->label();
		$grid->column('name', 'Es索引')->display(function () {
			return 'bf_' . $this->name;
		});
		$grid->column('desc', '描述');
		$grid->column('source_mapping', '映射Db表')->display(function () {
			$source = EsSourceMapping::where('es_index_id', $this->id)->distinct()->get('db_tables_id')->toArray();
			$data = [];
			foreach ($source as $value) {
				$data[] = DbTables::find($value['db_tables_id'])->table_name;
			}
			return $data;
		})->label()->width(200);
		$grid->column('batch_size', '批量执行大小');
		$grid->column('data_status', '状态')->using(EsIndex::DATA_STATUS, '未知')->label([
			EsIndex::STATUS_NORMAL => 'success',
			EsIndex::STATUS_DELETE => 'warning'
		]);
		$grid->actions(function (Actions $actions) {
			$actions->disableDelete();
			$actions->disableEdit();
			$actions->append("<a href=\"/admin/EsStandard/es-index/{$actions->row->id}/basic/edit\" class=\"btn btn-primary btn-xs\">编辑</a>");

		});
		return $grid;
	}

	public function setting(Content $content, $id = 0, $active = 'basic')
	{
		$basic = $mapping = $column = false;
		if ($active == 'basic') $basic = true;
		if ($active == 'mapping') $mapping = true;
		if ($active == 'column') $column = true;
		$tab = new Tab();
		//基础信息
		$baseInfoForm = $this->basicForm($id);
		$tab->add('Es索引信息', $baseInfoForm, $basic, 'basic');
		if ($id) {
			$tab->add('映射设置', $this->mappingGrid($id), $mapping, 'mapping');
			$tab->add('字段设置', $this->columnGrid($id), $column, 'column');
		}
		return $content
			->header($this->title)
			->description('Es索引信息')
			->breadcrumb([
				'text' => 'Es索引管理',
				'url' => '/EsStandard/es-index'
			], ['text' => 'Es索引信息'])
			->row($tab);
	}

	protected function basicForm($id = 0)
	{
		if ($id) {
			$data = EsIndex::find($id)->toArray();
		} else {
			$data = [];
		}
		$form = new Form($data);
		$form->select('es_instance_id', 'Es实例名称')->options(
			EsInstance::all()->pluck(
				'name',
				'id'
			)
		)->setWidth(4, 2)->required();
		$form->text('name', 'Es索引')->setWidth(4, 2)->required();
		$form->text('desc', '描述');
		$form->number('batch_size', '批量执行大小')->default(100)->max(2000)->required()->help("执行同步任务时每次处理的条数");
		$form->radio('data_status', '状态')->options(EsIndex::DATA_STATUS)->default(1)->required();
		$form->hidden('add_time');
		$form->hidden('update_time');
		$form->hidden('add_username');
		$form->hidden('update_username');
		$form->action('/admin/EsStandard/es-index/save/' . $id);
		return $form;
	}
	
	public function basicSave(Request $request, $id)
	{
		$res = $request->all();
		$data = [
			'es_instance_id' => $res['es_instance_id'] ?? 0,
			'name' => $res['name'] ?? '',
			'desc' => $res['desc'] ?? '',
			'batch_size' => $res['batch_size'] ?? 0,
			'data_status' => $res['data_status'] ?? 1
		];

		try {
			if ($id > 0) {
				$msg = '编辑成功';
				// 编辑
				$data['update_time'] = time();
				$data['update_username'] = Admin::user()->username;

				EsIndex::where('id', $id)->update($data);
			} else {
				$msg = '添加成功';
				// 新增
				$data['add_username'] = Admin::user()->username;
				$data['update_username'] = Admin::user()->username;
				$data['add_time'] = time();
				$data['update_time'] = time();

				$id = EsIndex::query()->insertGetId($data);
			}

			$success = new MessageBag([
				'title' => $msg
			]);
			return redirect('/admin/EsStandard/es-index/' . $id . '/basic/edit')->with(compact('success'));
		} catch (\Exception $e) {
			$error = new MessageBag([
				'title' => $e->getMessage()
			]);
			return back()->with(compact('error'));
		}
	}

	// 映射管理
	public function mappingGrid($id)
	{
		$grid = new Grid(new EsSourceMapping());
		$grid->model()->where(['es_index_id' => $id])->orderBy('id');
		$grid->disableFilter();
		$grid->disableExport();
		$grid->disableBatchActions();
		$grid->disableCreateButton();
		$grid->disablePagination();

		$grid->tools(function (Grid\Tools $tool) use ($id) {
			$tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增映射', '',
				url("/admin/EsStandard/es-db-mapping/{$id}/add")));
		});

		$grid->column('id', 'ID');
		$grid->column('es_column_name', 'es字段');
		$grid->column('db_tables_id', '映射数据表')->display(function () {
			return DbTables::find($this->db_tables_id)->table_name;
		});
		$grid->column('db_column_name', '映射db字段');
		$grid->column('mapping_type', '映射类型')->using([1 => '一对一', 2 => '一对多'])->label([
			1 => 'success',
			2 => 'success'
		]);
		$grid->column('is_main_table', '是否是主表')->using([1 => '是', 0 => '否'])->label([
			1 => 'success',
			0 => 'default'
		]);;
		$grid->column('is_must', '相对于Es是否必须')->using([1 => '是', 0 => '否'])->label([
			1 => 'success',
			0 => 'default'
		]);
		$grid->column('condition', '过滤条件')->display(function () {
			$filter = EsFilterRule::where(['es_index_id' => $this->es_index_id, 'db_tables_id' => $this->db_tables_id])->get()->toArray();
			$data = [];
			foreach ($filter as $value) {
			    if (!empty($value['raw_sql'])) {
                    $data[] = $value['raw_sql'];
                } else {
                    $data[] = $value['column_name'] . ' ' . $value['condition'] . ' ' . $value['value'];
                }
			}
			return $data;
		})->label();
		$grid->actions(function (Actions $actions) use ($id) {
			$actions->disableEdit();
			$actions->disableDelete();
			$actions->append("<a href=\"/admin/EsStandard/es-db-mapping/{$id}/" . $actions->row->id . "/edit\" class=\"btn btn-primary btn-xs \">编辑</a>");
			$actions->append("<a href=\"/admin/EsStandard/es-db-mapping/{$id}/" . $actions->row->id . "/delete\" class=\"btn btn-primary btn-xs \" onclick=\"return confirm('确认删除？');\">删除</a>");
		});

		return $grid->render();
	}

	// 字段管理
	public function columnGrid($id)
	{
		$esIndex = EsIndex::query()->find($id)->toArray();
		$sourceMapping = EsSourceMapping::where('es_index_id', $id)->distinct()->get('db_tables_id')->toArray();
		$dbTablesId = array_column($sourceMapping, 'db_tables_id');
		$form = new \Encore\Admin\Form(new EsIndex());
		$form->footer(function (\Encore\Admin\Form\Footer $footer) {
			$footer->disableEditingCheck();
			$footer->disableCreatingCheck();
			$footer->disableViewCheck();
		});
		$form->tools(function (\Encore\Admin\Form\Tools $tools) {
			$tools->disableDelete();
			$tools->disableView();
			$tools->disableList();
		});
		$form->divider('字段设置');
		$form->table('column', null, function (NestedForm $nest) use ($id, $dbTablesId) {
			$nest->hidden('id');
			$nest->text('id', 'Id')->readonly();
			$nest->text('column_name', '字段')->required();
			$nest->select('column_type', 'Es字段类型')->options(EsIndex::COLUMN_TYPE)->setWidth(4, 2)->required();
			$nest->radio('column_is_index', '是否索引')->options([
				1 => '是',
				0 => '否'
			])->required();
            $nest->radio('column_is_keyword', '是否keyword')->options([
                1 => '是',
                0 => '否'
            ])->default(0)->required();
			$nest->radio('is_primary', '是否主键')->options([
				1 => '是',
				0 => '否'
			])->required();
			$nest->hidden('bind_id');
			$nest->select('db_tables_id', '绑定db数据表')->options(
				DbTables::whereIn('id', $dbTablesId)->get()->pluck('table_name', 'id')
			)->load('source_column_name', '/admin/EsStandard/db-tables/getColumns')->required();
			$nest->select('source_column_name', '绑定db字段')->options(function () use ($nest) {
				$key = $nest->getKey();
				if ($this->column[$key]['db_tables_id']) {
					$dbTable = DbTables::find($this->column[$key]['db_tables_id'])->toArray();
					return DbInstance::getColumnsById($dbTable['db_instance_id'], $dbTable['database'], $dbTable['tables'][0]);
				} else {
					return [];
				}
			})->required();
			$nest->select('bind_type', '绑定类型')->options(EsColumnBindShip::BIND_TYPE)->default(0)->required();
		})->setWidth(12, 1);
		$form->setAction("/admin/EsStandard/es-column/{$id}/save");

		if ($id) {
			$form->edit($id);
			$form->hidden('es_index_id')->value($id);
		}

		return $form;
	}

}